package main

import (
	"gitee.com/xingnan/toolbox/otp"
	"gitee.com/xingnan/toolbox/otp/totp"
	"strings"

	"bufio"
	"bytes"
	"encoding/base32"
	"fmt"
	"image/png"
	"io/ioutil"
	"os"
	"time"
)

func display(key *otp.Key, data []byte) {
	fmt.Printf("发行者:       %s\n", key.Issuer())
	fmt.Printf("帐户名称: %s\n", key.AccountName())
	fmt.Printf("密钥密文:       %s\n", key.Secret())
	fmt.Println("写入 qr-code.png....")
	ioutil.WriteFile("qr-code.png", data, 0644)
	fmt.Println("")
	fmt.Println("请立即将您的TOTP添加到您的OTP应用程序中！")
	fmt.Println("")
}

func promptForPasscode() string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("输入一次性密码: ")
	text, _ := reader.ReadString('\n')
	return text
}

// Demo function, not used in main
// Generates Passcode using a UTF-8 (not base32) secret and custom paramters
//
func GeneratePassCode(utf8string string) string {
	secret := base32.StdEncoding.EncodeToString([]byte(utf8string))
	passcode, err := totp.GenerateCodeCustom(secret, time.Now(), totp.ValidateOpts{
		Period:    30,
		Skew:      1,
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA512,
	})
	if err != nil {
		panic(err)
	}
	return passcode
}

func main() {
	key, err := totp.Generate(totp.GenerateOpts{
		Issuer:      "cloud-insight.com.cn",
		AccountName: "nan.xing@cloud-insight.com.cn",
		Period:      30,
		Algorithm:   2,
	})
	secret := key.Secret()
	fmt.Println("密钥：", secret)
	if err != nil {
		panic(err)
	}
	// Convert TOTP key into a PNG
	var buf bytes.Buffer
	img, err := key.Image(200, 200)
	if err != nil {
		panic(err)
	}
	png.Encode(&buf, img)

	// display the QR code to the user.
	display(key, buf.Bytes())

	// Now Validate that the user's successfully added the passcode.
	fmt.Println("验证TOTP...")
	for {
		passcode := strings.TrimSpace(promptForPasscode())

		valid, err := totp.ValidateCustom(passcode, secret, time.Now(), totp.ValidateOpts{Period: 60, Algorithm: 2, Digits: 6})
		fmt.Println("验证错误：", valid, err)
		if valid {
			println("passcode 有效!")
			continue
		} else {
			println("passcode 无效!")
			continue
		}
	}
}
